<?php

namespace plugin\ycMassage\app\model;


class MassageRegions extends Model
{
    public static function cacheCascaderOptions($options, $saas_appid)
    {
        $cachePath = public_path('uploads/ycMassage/regions');
        if (!is_dir($cachePath)) {
            mkdir($cachePath, 0777, true);
        }
        $cachePath = $cachePath . "Regions-{$saas_appid}.json";
        $content = json_encode($options, JSON_UNESCAPED_UNICODE);
        file_put_contents($cachePath, $content);
    }
    public static function getCache($saas_appid)
    {
        $cachePath = public_path('uploads/ycMassage/regions') . "Regions-{$saas_appid}.json";
        $options = [];
        if (is_file($cachePath)) {
            $options = json_decode(file_get_contents($cachePath), true);
            if ($options) {
                return $options;
            }
        }
        throw new \Exception('地区缓存文件不存在，请在内容-地区管理-执行缓存操作');
    }
    public static function organizeRecords($regions)
    {
        $organizedRegions = [];
        foreach ($regions as $region) {
            $organizedRegions[$region['id']] = $region;
            $organizedRegions[$region['id']]['children'] = [];
        }
        return $organizedRegions;
    }
    public static function buildTree($organized)
    {
        $tree = [];
        foreach ($organized as $id => $record) {
            if ($record['pid']) {
                $organized[$record['pid']]['children'][] = &$organized[$id];
            } else {
                $tree[] = &$organized[$id];
            }
        }
        return $tree;
    }
}
